package com.xfc.config.aspect;

import com.xfc.common.core.redis.RedisCache;
import com.xfc.config.MyAESUtil;
import com.xfc.config.Tools;
import com.xfc.wx.domain.ScWxUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 参数注入
 * @author lcj
 */
@Slf4j
@Aspect
@Component
public class InfoParamsAspect {

    @Autowired
    private RedisCache redisUtils;

    @Pointcut("@annotation(com.xfc.config.aspect.Token)")
    public void infoCut() {
    }

    @Around("infoCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature signature = ((MethodSignature) joinPoint.getSignature());
        //得到拦截的方法
        Method method = signature.getMethod();
        //获取方法上的注解
        Annotation parameterAnnotations = method.getAnnotation(Token.class);
        if (parameterAnnotations == null) {
            return joinPoint.proceed();
        }
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        String token = request.getHeader("token");
        String resToekn= MyAESUtil.Decrypt(token, Tools.USER_KRY);
        String[] str=resToekn.split(",");
        // 参数值
        Object[] args = joinPoint.getArgs();
        // 参数名
        String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        if (argNames.length>0&&argNames!=null){
            for (int i = 0; i < argNames.length; i++) {
                if ("wxUser".equals(argNames[i])){
                    if (Objects.nonNull(str)){
                        if (str.length==2){
                            ScWxUser user= redisUtils.getCacheObject(Tools.USER_TOKEN+str[0]);
                            //添加用户
                            args[i]=user;
                        }
                    }
                }
            }
        }
        return joinPoint.proceed(args);
    }

}
